<script setup lang="ts">
import {ref, reactive, onMounted, computed} from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { createOrder } from '../../api/order'
import { pageHotel } from '../../api/hotel'
import { pageRoom } from '../../api/room'
import axios from "axios";

const router = useRouter()
const orderForm = ref(null)
const loading = ref(false)

const http = axios.create({
  // baseURL:"http://127.0.0.1:8080",
  timeout:5000
});
const form = reactive({
  orderName: '',
  hotelId: '',
  roomId: '',
  checkInDate: '',
  checkOutDate: '',
  roomPrice:'',
  remark: ''
})

// 验证规则
const rules = reactive({
  orderName: [
    { required: true, message: '请输入订单名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在2到50个字符', trigger: 'blur' }
  ],
  hotelId: [
    { required: true, message: '请选择酒店', trigger: 'change' }
  ],
  roomId: [
    { required: true, message: '请选择房间类型', trigger: 'change' }
  ],
  checkInDate: [
    { required: true, message: '请选择入住日期', trigger: 'change' }
  ],
  checkOutDate: [
    { required: true, message: '请选择退房日期', trigger: 'change' }
  ]
})

// 酒店和房间选项
const hotelOptions = ref([])
const roomOptions = ref([])

// 获取酒店列表
const fetchHotels = async () => {
  try {
    const response = await pageHotel({ page: 1, pageSize: 100 })
    hotelOptions.value = response.data.records
  } catch (error) {
    ElMessage.error('获取酒店列表失败')
  }
}

// 酒店选择变化时获取房间列表
const handleHotelChange = async (hotelId) => {
  form.roomId = ''
  if (!hotelId) {
    roomOptions.value = []
    return
  }

  try {
    const response = await pageRoom({ hotelId, page: 1, pageSize: 100 })
    roomOptions.value = response.data.records
  } catch (error) {
    ElMessage.error('获取房间列表失败')
  }
}

// 禁用入住日期（只能选择今天及以后的日期）
const disabledCheckInDate = (time) => {
  return time.getTime() < Date.now() - 86400000
}

// 禁用退房日期（只能选择入住日期之后的日期）
const disabledCheckOutDate = (time) => {
  if (!form.checkInDate) return true
  const checkInDate = new Date(form.checkInDate)
  return time.getTime() <= checkInDate.getTime()
}
const filteredRooms = computed(() => {
  if (!form.hotelId) return []
  return roomOptions.value.filter(room => room.hotelId === form.hotelId)
})


// 提交表单
// const submitForm = () => {
//   orderForm.value.validate(async (valid) => {
//     if (!valid) return
//
//     try {
//       loading.value = true
//
//       // 获取选中的房间信息
//       const selectedRoom = roomOptions.value.find(r => r.id === form.roomId)
//
//       // 准备订单数据
//       const orderData = {
//         orderName: form.orderName,
//         hotelId: form.hotelId,
//         roomId: form.roomId,
//         price: selectedRoom.price,
//         checkInDate: form.checkInDate,
//         checkOutDate: form.checkOutDate,
//         remark: form.remark
//       }
//
//       // 调用API创建订单
//       const response = await createOrder(orderData)
//
//       ElMessage.success('订单创建成功')
//
//       // 跳转到支付页面
//       router.push({
//         path: `/order/payment/${response.data.id}`
//       })
//     } catch (error) {
//       ElMessage.error(error.message || '订单创建失败')
//     } finally {
//       loading.value = false
//     }
//   })
// }
const  submitForm= async () => {
console.info(form)
  if (form.roomId) {
    const [roomId, roomPrice] = form.roomId.split(',')
    console.log('房间ID:', roomId)
    form.roomId = roomId
    form.roomPrice = roomPrice
    console.info(form)
    console.log('房间价格:', roomPrice)
  }
  const orderData = {
    orderName: form.orderName,
    hotelId: form.hotelId,
    roomId: form.roomId,
    price: form.roomPrice,
    checkInDate: form.checkInDate,
    checkOutDate: form.checkOutDate,
    remark: form.remark
  }
    const {data: res} = await http.post("/api/order/create", orderData)
    if (res.code !== 200) {
      loading.value = false
      return ElMessage.error("添加用户失败");
    }
    ElMessage.success("添加用户成功");
    loading.value = false
    router.push({path: `/order/list`})
  }
// 重置表单
  const resetForm = () => {
    orderForm.value.resetFields()
    roomOptions.value = []
  }

// 初始化加载酒店列表
  onMounted(() => {
    fetchHotels()
  })
</script>

<template>
  <div class="order-create-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>创建新订单</h3>
        </div>
      </template>

      <el-form
          :model="form"
          :rules="rules"
          ref="orderForm"
          label-width="120px"
          label-position="top"
      >
        <el-form-item label="订单名称" prop="orderName">
          <el-input v-model="form.orderName" placeholder="请输入订单名称" />
        </el-form-item>

        <el-form-item label="关联酒店" prop="hotelId">
          <el-select
              v-model="form.hotelId"
              placeholder="请选择酒店"
              @change="handleHotelChange"
              filterable
          >
            <el-option
                v-for="hotel in hotelOptions"
                :key="hotel.id"
                :label="hotel.hotelName"
                :value="hotel.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="房间类型" prop="roomId">
          <el-select
              v-model="form.roomId"
              placeholder="请先选择酒店"
              :disabled="!form.hotelId"
          >
            <el-option
                v-for="room in filteredRooms"
                :key="room.id"
                :label="`${room.roomType} - ¥${room.price}`"
                :value="`${room.id},${room.price}`"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="入住日期" prop="checkInDate">
          <el-date-picker
              v-model="form.checkInDate"
              type="date"
              placeholder="选择入住日期"
              :disabled-date="disabledCheckInDate"
          />
        </el-form-item>

        <el-form-item label="退房日期" prop="checkOutDate">
          <el-date-picker
              v-model="form.checkOutDate"
              type="date"
              placeholder="选择退房日期"
              :disabled="!form.checkInDate"
              :disabled-date="disabledCheckOutDate"
          />
        </el-form-item>

        <el-form-item label="备注信息">
          <el-input
              v-model="form.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入备注信息（可选）"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="loading">提交订单</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<style scoped lang="scss">
.order-create-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.card-header {
  text-align: center;
}

.el-form-item {
  margin-bottom: 22px;
}

.el-select, .el-date-editor {
  width: 100%;
}
</style>